package com.samehope.ar.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.samehope.ar.constant.DelFlagEnum;
import com.samehope.ar.constant.IsTempEnum;
import com.samehope.ar.dto.*;
import com.samehope.ar.entity.PatrolRoute;
import com.samehope.ar.entity.TaskNormal;
import com.samehope.ar.mapper.TaskNormalMapper;
import com.samehope.ar.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.samehope.ar.util.SessionUtil;
import com.samehope.ar.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 正式巡检任务 服务实现类
 * </p>
 *
 * @author Zhang Luo
 * @since 2019-12-23
 */
@Service
public class TaskNormalServiceImpl extends ServiceImpl<TaskNormalMapper, TaskNormal> implements ITaskNormalService {

    @Autowired
    private ITaskPointService taskPointService;

    @Autowired
    private IPatrolRouteService patrolRouteService;

    @Autowired
    private ITaskRouteService taskRouteService;

    @Autowired
    private ITaskItemService taskItemService;

    @Autowired
    private ITaskItemChildService taskItemChildService;

    /**
     * 任务列表
     * @param paginationParam
     * @param param
     * @return
     */
    @Override
    public PaginationDataVO<TaskTimeVO> findByParam(PaginationParam paginationParam, TaskQueryParam param){
        Long companyId = SessionUtil.getCompanyId();
        Long projectId = SessionUtil.getProjectId();
        Page<TaskTimeVO> page = new Page<>(paginationParam.getPageNum(), paginationParam.getPageSize());
        //查询时间列表
        List<TaskTimeVO> taskTimes = this.baseMapper.findTaskTime(
                page
                ,companyId
                ,projectId
                ,param.getPlanId()
                ,param.getTeamId()
                ,param.getUserId()
                ,param.getStartDate()
                ,param.getEndDate()
                ,param.getTaskName()
                ,param.getTaskType()
                ,param.getTaskStatus());

        taskTimes.forEach(taskTime ->{
            //查询该任务时间下的任务信息
            if(taskTime != null && taskTime.getTaskTime() != null) {
                List<TaskNormalDataVO> taskNormals = this.baseMapper.findByParam(
                        companyId
                        , projectId
                        , param.getPlanId()
                        , param.getTeamId()
                        , param.getUserId()
                        , taskTime.getTaskTime()
                        , param.getTaskName()
                        , param.getTaskType()
                        , param.getTaskStatus());
                taskTime.setTaskNormalDataVO(taskNormals);
            }
        });
        page.setRecords(taskTimes);
        return PaginationDataVO.of(page);
    }

    /**
     * 根据计划任务生成下周的正式任务信息
     * @param vo
     */
    @Override
    public void insertByPlans(PatrolTaskPlanWeekDetailVO vo){
        this.baseMapper.insertByPlans(vo);
    }

    /**
     * 根据用户查找单独执行的正式任务
     * @param userId
     * @return
     */
    @Override
    public List<TaskNormal> findTaskNormalByUserNotOver(Long userId) {
        return this.baseMapper.findTaskNormalNotOverByProjectAndUser(SessionUtil.getProjectId(), userId);
    }

    /**
     * 删除快照信息
     * @param taskTime
     */
    @Override
    public void delByTaskTime(String taskTime){
        this.baseMapper.delByTaskTime(taskTime);
    }

    /**
     * 删除未执行任务快照
     * @param planId
     */
    @Override
    public void delByUnFinishTask(Long planId){
        this.baseMapper.delByUnFinishTask(planId, SessionUtil.getUserId());
    }

    /**
     * 更新单个任务信息
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(TaskNormalUpdateParam param){

        Long companyId = SessionUtil.getCompanyId();
        Long projectId = SessionUtil.getProjectId();

        //增加临时线路逻辑
        if(null == param.getRouteId()) {
            RouteAndParam routeAndParam = new RouteAndParam();
            routeAndParam.setRouteName(projectId + "-"  + param.getTaskName() + "-临时线路" + IdUtil.randomUUID());
            routeAndParam.setIsTemp(IsTempEnum.TEMP.getCode());
            if (StringUtils.isBlank(param.getPointIds())) {
                throw new IllegalArgumentException("请选择巡检点");
            }
            String[] points = param.getPointIds().split(",");
            List<RoutePointParam> lists = new ArrayList<RoutePointParam>();
            for (int i = 0;i < points.length; i++){
                RoutePointParam pointParam = new RoutePointParam();
                pointParam.setPointId(Long.valueOf(points[i]));
                pointParam.setSortNo(Long.valueOf(i+1));
                lists.add(pointParam);
            }
            routeAndParam.setPoints(lists);
            Long routeId = patrolRouteService.add(routeAndParam);
            param.setRouteId(routeId);
        }

        //删除以前的线路快照信息
        taskRouteService.delByTaskId(param.getId());
        taskPointService.delByTaskId(param.getId());
        taskRouteService.insertByTask(param.getId(), param.getRouteId());
        taskPointService.insertByTask(param.getId(), param.getRouteId());

        //更新任务记录
        TaskNormal taskNormal = new TaskNormal();
        taskNormal.setId(param.getId());
        taskNormal.setTaskName(param.getTaskName());
        taskNormal.setPlanExecBys(param.getPlanExecBys());
        taskNormal.setRouteId(param.getRouteId());
        taskNormal.setTeamId(param.getTeamId());
        taskNormal.setIsRecordLocation(param.getIsRecordLocation());
        taskNormal.setRemarks(param.getRemarks());
        taskNormal.setUpdateBy(SessionUtil.getUserId());
        this.baseMapper.updateById(taskNormal);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void del(Long taskId){

        //删除任务记录
        TaskNormal taskNormal = new TaskNormal();
        taskNormal.setId(taskId);
        taskNormal.setDelFlag(DelFlagEnum.DELETED.getCode());
        taskNormal.setUpdateBy(SessionUtil.getUserId());
        this.baseMapper.updateById(taskNormal);

        //删除该任务巡检项明细快照
        taskItemChildService.delByTaskId(taskId);
        //删除该任务巡检项快照
        taskItemService.delByTaskId(taskId);
        //删除该任务巡检点快照
        taskPointService.delByTaskId(taskId);
        //删除该任务巡检线路快照
        taskRouteService.delByTaskId(taskId);
    }

    @Override
    public TaskNormalDetailVO detail(Long taskId){
        return this.baseMapper.findByTaskId(SessionUtil.getCompanyId()
                                            ,SessionUtil.getProjectId()
                                            ,taskId);
    }

    @Override
    public List<FormSelectVO> getTaskName(){
        return this.baseMapper.getTaskName(SessionUtil.getCompanyId(), SessionUtil.getProjectId());
    }
}
